|
|
|
|
|
|
|
It can also be called by using literal values for the input parameters and variables for the output parameters: |
|
|
|
|
|
|
|
|
nArea = 0
nPerm = 0
CalcRectangle 4, 10, nArea, nPerm |
|
|
|
|
|
|
|
|
Passing parameters to a procedure in this way is known as passing by reference. In this case, the variable name passed to the procedure and the variable name used in the procedure both refer to (reference) the same location in memory. When entering a function or procedure declaration, you can explicitly indicate "by reference" parameters with the ByRef keyword, as in the following example: |
|
|
|
|
|
|
|
|
Sub ChangeString(ByRef AnyString As String)
AnyString = "After"
End Sub
Dim sSampleString As String
sSampleString = "Before"
ChangeString sSampleString |
|
|
|
|
|
|
|
|
The first three lines of code define a simple subroutine that changes the contents of a string passed as a parameter. The ByRef keyword indicates that any changes made to the parameter will be reflected in the variable passed to the procedure. In other words, changing the value of AnyString within the procedure causes the value of sSampleString to be changed as well. This capability enables the procedure to modify the value that is then passed back to the calling code. |
|
|
|
|
|
|
|
|
You can also pass a parameter to a procedure by value. This approach causes the procedure to use a copy of the information that was passed to it, which prevents the procedure code from modifying the value used by the calling program. By default, when you declare a parameter for a procedure, the passing by reference approach is used. To modify this behavior, you must explicitly tell Visual Basic to pass the parameter by value. Do so by placing the ByVal keyword in the parameter list before each variable that is to be passed by value, as illustrated in the following code: |
|
|
|
|
|
|
|
|
Sub CalcRectangle(ByVal nWidth As Integer, ByVal nHeight As Integer, _
_nArea, nPerimeter As Integer) |
|
|
|
|
CAUTION
|
|
|
|
|
If you are passing parameters by reference, you need to explicitly declare the variable in the calling program and in the procedure, and you need to be sure that the variable types are the same. |
|
|
|
|
|
|
|
|
|
|
Exiting a Procedure Early |
|
|
|
|
|
|
|
|
As your programs, and therefore your procedures, grow in complexity, sometimes you might not need to execute all the commands in the procedure. If you need to exit the procedure before all the commands have been executed, you can use the Exit Sub statement. |
|
|
|
|
|